<template>
	<view class="page-container">
		<!-- 顶部导航栏（统一风格） -->
		<u-navbar bgColor="#F5F9FC" :placeholder="true">
			<view slot="left" class="navbar-left">
				<navigator url="/pageNew/pages/invoice/index" class="back-navigator">
					<view class="back-content">
						<u-icon color="#1e88e5" name="arrow-left"></u-icon>
						<text class="navbar-title">编辑发票</text>
					</view>
				</navigator>
			</view>
		</u-navbar>

		<!-- 主内容区 -->
		<view class="content-container">
			<form class="invoice-form" @submit="saveInvoice">
				<view class="form-card">
					<!-- 发票类型 -->
					<view class="form-row">
						<view class="form-field">
							<view class="label-wrapper">
								<text class="field-label">发票类型</text>
								<text class="required-star">*</text>
							</view>
							<picker class="picker-field" mode="selector" :range="invoiceTypes" range-key="label"
								v-model="selectedInvoiceType" @change="onInvoiceTypeChange">
								<view class="picker-display">
									{{ selectedInvoiceType === -1 ? '请选择发票类型' : invoiceTypes[selectedInvoiceType].label }}
								</view>
							</picker>
						</view>
					</view>

					<!-- 发票标题 -->
					<view class="form-row">
						<view class="form-field">
							<view class="label-wrapper">
								<text class="field-label">发票标题</text>
								<text class="required-star">*</text>
							</view>
							<input class="text-input" type="text" placeholder="请输入发票标题" v-model="invoiceTitle"
								@input="validateTitle">
						</view>
					</view>

					<!-- 发票号码（根据状态判断是否禁用） -->
					<view class="form-row">
						<view class="form-field">
							<view class="label-wrapper">
								<text class="field-label">发票号码</text>
								<text class="required-star">*</text>
							</view>
							<input class="text-input" type="text" placeholder="请输入发票号码" v-model="invoiceNo"
								@input="validateInvoiceNo" :disabled="invoice.status !== 'pending'"
								:style="invoice.status !== 'pending' ? 'background-color: #f3f4f6;' : ''">
						</view>
					</view>

					<!-- 开票日期 -->
					<view class="form-row">
						<view class="form-field">
							<view class="label-wrapper">
								<text class="field-label">开票日期</text>
								<text class="required-star">*</text>
							</view>
							<picker class="picker-field" mode="date" start="2010-01-01" :end="currentDate"
								:value="invoiceDate" @change="onInvoiceDateChange">
								<view class="picker-display">
									{{ invoiceDate || '请选择开票日期' }}
								</view>
							</picker>
						</view>
					</view>

					<!-- 开票方 -->
					<view class="form-row">
						<view class="form-field">
							<view class="label-wrapper">
								<text class="field-label">开票方</text>
								<text class="required-star">*</text>
							</view>
							<input class="text-input" type="text" placeholder="请输入开票方名称" v-model="seller"
								@input="validateSeller">
						</view>
					</view>

					<!-- 发票金额 -->
					<view class="form-row">
						<view class="form-field">
							<view class="label-wrapper">
								<text class="field-label">发票金额</text>
								<text class="required-star">*</text>
							</view>
							<view class="amount-input-wrapper">
								<text class="currency-symbol">¥</text>
								<input class="amount-input" type="number" placeholder="请输入发票金额" v-model="invoiceAmount"
									@input="validateAmount">
							</view>
						</view>
					</view>

					<!-- 税率 -->
					<view class="form-row">
						<view class="form-field">
							<view class="label-wrapper">
								<text class="field-label">税率</text>
								<text class="required-star">*</text>
							</view>
							<view class="tax-rate-input-wrapper">
								<input class="tax-rate-input" type="number" placeholder="请输入税率" v-model="taxRate"
									@input="validateTaxRate">
								<text class="percent-symbol">%</text>
							</view>
						</view>
					</view>

					<!-- 税额（禁用状态） -->
					<view class="form-row">
						<view class="form-field">
							<view class="label-wrapper">
								<text class="field-label">税额</text>
							</view>
							<view class="tax-amount-input-wrapper">
								<text class="currency-symbol">¥</text>
								<input class="tax-amount-input" type="number" placeholder="请输入税额" v-model="taxAmount"
									disabled>
							</view>
						</view>
					</view>

					<!-- 备注 -->
					<view class="form-row">
						<view class="form-field textarea-field-wrapper">
							<view class="label-wrapper">
								<text class="field-label">备注</text>
							</view>
							<textarea class="textarea-field" placeholder="请输入备注信息" v-model="invoiceRemark"
								rows="3"></textarea>
						</view>
					</view>
				</view>
			</form>
		</view>

		<!-- 底部固定按钮区域 -->
		<view class="fixed-bottom-buttons">
			<navigator open-type="navigateBack" :delta="1" class="btn cancel-btn" @click.stop>
				取消
			</navigator>
			<button class="btn save-btn" @click="saveInvoice">
				保存
			</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 发票ID
				invoiceId: '',

				// 发票类型
				invoiceTypes: [{
						value: 'special',
						label: '增值税专用发票'
					},
					{
						value: 'ordinary',
						label: '增值税普通发票'
					},
					{
						value: 'electronic',
						label: '电子发票'
					},
					{
						value: 'motor',
						label: '机动车销售统一发票'
					},
					{
						value: 'other',
						label: '其他发票'
					}
				],
				selectedInvoiceType: -1,

				// 发票信息
				invoice: {},
				invoiceTitle: '',
				invoiceNo: '',
				invoiceDate: '',
				currentDate: this.formatDate(new Date()),
				seller: '',
				invoiceAmount: '',
				taxRate: '',
				taxAmount: '',
				invoiceRemark: ''
			};
		},
		onLoad(options) {
			console.log('编辑发票页面加载完成', options);

			// 获取发票ID
			this.invoiceId = options.id;

			// 加载发票数据
			this.loadInvoice();
		},
		watch: {
			// 监听金额和税率变化，自动计算税额
			invoiceAmount() {
				this.calculateTaxAmount();
			},
			taxRate() {
				this.calculateTaxAmount();
			}
		},
		methods: {
			// 加载发票数据
			loadInvoice() {
				// 获取本地存储的发票数据
				let invoices = uni.getStorageSync('invoices') || [];

				// 查找对应的发票
				const foundInvoice = invoices.find(inv => inv.id === this.invoiceId);

				if (foundInvoice) {
					this.invoice = foundInvoice;

					// 填充表单数据
					this.selectedInvoiceType = this.invoiceTypes.findIndex(type => type.value === foundInvoice.type);
					this.invoiceTitle = foundInvoice.title;
					this.invoiceNo = foundInvoice.invoiceNo;
					this.invoiceDate = foundInvoice.date;
					this.seller = foundInvoice.seller;
					this.invoiceAmount = foundInvoice.amount.toString();
					this.taxRate = foundInvoice.taxRate.toString();
					this.taxAmount = foundInvoice.taxAmount.toString();
					this.invoiceRemark = foundInvoice.remark || '';
				} else {
					// 如果本地存储中没有找到，使用默认数据
					this.invoiceDate = this.currentDate;
				}
			},

			// 格式化日期
			formatDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');

				return `${year}-${month}-${day}`;
			},

			// 发票类型变更
			onInvoiceTypeChange(e) {
				this.selectedInvoiceType = e.detail.value;
			},

			// 开票日期变更
			onInvoiceDateChange(e) {
				this.invoiceDate = e.detail.value;
			},

			// 验证发票标题
			validateTitle() {
				if (!this.invoiceTitle) {
					return false;
				}
				return true;
			},

			// 验证发票号码
			validateInvoiceNo() {
				if (!this.invoiceNo) {
					return false;
				}
				return true;
			},

			// 验证开票方
			validateSeller() {
				if (!this.seller) {
					return false;
				}
				return true;
			},

			// 验证发票金额
			validateAmount() {
				if (!this.invoiceAmount || parseFloat(this.invoiceAmount) <= 0) {
					return false;
				}
				return true;
			},

			// 验证税率
			validateTaxRate() {
				if (this.taxRate === '' || parseFloat(this.taxRate) < 0 || parseFloat(this.taxRate) > 100) {
					return false;
				}
				return true;
			},

			// 计算税额
			calculateTaxAmount() {
				if (this.validateAmount() && this.validateTaxRate()) {
					const amount = parseFloat(this.invoiceAmount);
					const rate = parseFloat(this.taxRate) / 100;
					this.taxAmount = (amount * rate).toFixed(2);
				} else {
					this.taxAmount = '';
				}
			},

			// 保存发票
			saveInvoice() {
				// 表单验证
				if (this.selectedInvoiceType === -1) {
					uni.showToast({
						title: '请选择发票类型',
						icon: 'none'
					});
					return;
				}

				if (!this.validateTitle()) {
					uni.showToast({
						title: '请输入发票标题',
						icon: 'none'
					});
					return;
				}

				if (!this.validateInvoiceNo()) {
					uni.showToast({
						title: '请输入发票号码',
						icon: 'none'
					});
					return;
				}

				if (!this.invoiceDate) {
					uni.showToast({
						title: '请选择开票日期',
						icon: 'none'
					});
					return;
				}

				if (!this.validateSeller()) {
					uni.showToast({
						title: '请输入开票方名称',
						icon: 'none'
					});
					return;
				}

				if (!this.validateAmount()) {
					uni.showToast({
						title: '请输入有效的发票金额',
						icon: 'none'
					});
					return;
				}

				if (!this.validateTaxRate()) {
					uni.showToast({
						title: '请输入有效的税率(0-100%)',
						icon: 'none'
					});
					return;
				}

				// 获取本地存储的发票数据
				let invoices = uni.getStorageSync('invoices') || [];

				// 查找对应的发票
				const index = invoices.findIndex(inv => inv.id === this.invoiceId);

				if (index !== -1) {
					// 更新发票数据
					invoices[index].title = this.invoiceTitle;
					invoices[index].invoiceNo = this.invoiceNo;
					invoices[index].type = this.invoiceTypes[this.selectedInvoiceType].value;
					invoices[index].date = this.invoiceDate;
					invoices[index].seller = this.seller;
					invoices[index].amount = parseFloat(this.invoiceAmount);
					invoices[index].taxRate = parseFloat(this.taxRate);
					invoices[index].taxAmount = parseFloat(this.taxAmount);
					invoices[index].remark = this.invoiceRemark || '';

					// 保存到本地存储
					uni.setStorageSync('invoices', invoices);

					// 显示成功提示
					uni.showToast({
						title: '发票更新成功',
						icon: 'success'
					});

					// 返回发票管理列表页面
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						});
					}, 1500);
				} else {
					uni.showToast({
						title: '未找到发票记录',
						icon: 'none'
					});
				}
			}
		}
	};
</script>

<style>
	/* 全局容器样式 */
	.page-container {
		min-height: 100vh;
		background-color: #f9fafb;
		position: relative;
	}

	/* 导航栏样式 */
	.navbar-left {
		display: flex;
		align-items: center;
	}

	.back-navigator {
		display: flex;
		align-items: center;
	}

	.back-content {
		display: flex;
		align-items: center;
	}

	.navbar-title {
		font-size: 16px;
		font-weight: 600;
		color: #1e88e5;
		margin-left: 8px;
	}

	/* 内容容器样式 - 控制表单宽度与边距，避免被底部按钮遮挡 */
	.content-container {
		margin: 0 auto;
		padding: 16px;
		padding-bottom: 80px;
		box-sizing: border-box;
	}

	/* 表单卡片样式 - 白色背景与阴影，提升层次感 */
	.form-card {
		background-color: #ffffff;
		border-radius: 8px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		padding: 16px;
	}

	/* 表单行样式 - 控制每行间距 */
	.form-row {
		margin-bottom: 14px;
		padding: 4px 0;
	}

	/* 表单字段容器 - 水平布局，标签与输入框同行 */
	.form-field {
		display: flex;
		flex-direction: row;
		align-items: center;
		width: 100%;
	}

	/* 标签容器 - 固定宽度确保对齐，控制标签与输入框间距 */
	.label-wrapper {
		width: 100px;
		flex-shrink: 0;
		display: flex;
		align-items: center;
		padding-right: 12px;
		box-sizing: border-box;
	}

	.field-label {
		font-size: 14px;
		color: #6b7280;
	}

	/* 必填项星号样式 */
	.required-star {
		color: #f44336;
		margin-left: 4px;
	}

	/* 基础输入框样式 - 统一高度、边框与圆角 */
	.text-input {
		flex-grow: 1;
		height: 40px;
		padding: 0 12px;
		border: 1px solid #e5e7eb;
		border-radius: 6px;
		font-size: 14px;
		color: #1f2937;
		box-sizing: border-box;
	}

	/* 输入框占位符样式 - 浅灰色确保可见性 */
	.text-input::placeholder {
		color: #9ca3af;
		opacity: 1;
	}

	/* 禁用状态输入框样式（如发票号码禁用时） */
	.text-input:disabled,
	.text-input[disabled] {
		background-color: #f3f4f6;
		cursor: not-allowed;
	}

	/* 选择器样式 - 与输入框视觉统一 */
	.picker-field {
		flex-grow: 1;
	}

	.picker-display {
		width: 100%;
		height: 40px;
		line-height: 40px;
		padding: 0 12px;
		border: 1px solid #e5e7eb;
		border-radius: 6px;
		font-size: 14px;
		color: #1f2937;
		box-sizing: border-box;
	}

	/* 金额输入框样式 - 带人民币符号前缀 */
	.amount-input-wrapper {
		flex-grow: 1;
		position: relative;
	}

	.currency-symbol {
		position: absolute;
		left: 12px;
		top: 10px;
		color: #6b7280;
	}

	.amount-input {
		width: 100%;
		height: 40px;
		padding: 0 12px 0 32px;
		border: 1px solid #e5e7eb;
		border-radius: 6px;
		font-size: 14px;
		color: #1f2937;
		box-sizing: border-box;
	}

	/* 税率输入框样式 - 带百分号后缀 */
	.tax-rate-input-wrapper {
		flex-grow: 1;
		position: relative;
	}

	.tax-rate-input {
		width: 100%;
		height: 40px;
		padding: 0 32px 0 12px;
		border: 1px solid #e5e7eb;
		border-radius: 6px;
		font-size: 14px;
		color: #1f2937;
		box-sizing: border-box;
	}

	.percent-symbol {
		position: absolute;
		right: 12px;
		top: 10px;
		color: #6b7280;
	}

	/* 税额输入框样式 - 禁用状态，带人民币符号 */
	.tax-amount-input-wrapper {
		flex-grow: 1;
		position: relative;
	}

	.tax-amount-input {
		width: 100%;
		height: 40px;
		padding: 0 12px 0 32px;
		border: 1px solid #e5e7eb;
		border-radius: 6px;
		font-size: 14px;
		color: #1f2937;
		background-color: #f3f4f6;
		box-sizing: border-box;
		cursor: not-allowed;
	}

	/* 文本域样式 - 顶部与标签对齐，控制最小高度 */
	.textarea-field-wrapper {
		align-items: flex-start;
		padding-top: 8px;
	}

	.textarea-field {
		flex-grow: 1;
		min-height: 80px;
		padding: 8px 12px;
		border: 1px solid #e5e7eb;
		border-radius: 6px;
		font-size: 14px;
		color: #1f2937;
		resize: vertical;
		box-sizing: border-box;
	}

	.textarea-field::placeholder {
		color: #9ca3af;
		opacity: 1;
	}

	/* 底部固定按钮区域 - 固定在页面底部，与表单宽度对齐 */
	.fixed-bottom-buttons {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
		padding: 12px 16px;
		box-sizing: border-box;
		display: flex;
		gap: 12px;
		max-width: 750rpx;
		margin: 0 auto;
	}

	/* 按钮通用样式 - 平分宽度，统一高度与字体 */
	.btn {
		flex: 1;
		height: 44px;
		line-height: 44px;
		text-align: center;
		border-radius: 8px;
		font-size: 15px;
		font-weight: 500;
		transition: all 0.2s ease;
	}

	/* 取消按钮样式 - 浅灰色背景，区分次要操作 */
	.cancel-btn {
		background-color: #f3f4f6;
		color: #4b5563;
		text-decoration: none;
	}

	.cancel-btn:active {
		background-color: #e5e7eb;
	}

	/* 保存按钮样式 - 主题色背景，突出主要操作 */
	.save-btn {
		background-color: #1e88e5;
		color: #ffffff;
		border: none;
	}

	.save-btn:active {
		background-color: #1976d2;
	}
</style>